<template>
  <view class="main">
    <scroll-view
      scroll-y
      style="height: 100%"
      @scroll="handleScroll"
      @scrolltolower="handleScrollToLolower"
    >
      <view class="scroll-wrapper">
        <view id="categorize" class="categorize-list">
          <view
            :class="[
              'categorize',
              currentCategorizeId == item.id ? 'active' : '',
            ]"
            v-for="(item, index) in categorizeList"
            :key="index"
            @click="switchCategorize(item)"
          >
            <text class="text">{{ item.name }}</text>
          </view>
        </view>
        <view class="goods-list p-20">
          <template v-if="list.length">
            <view
              v-for="item in list"
              :key="item.id"
              style="margin-bottom: 20rpx"
            >
              <my-goods :data="item"></my-goods>
            </view>
          </template>
          <template v-else>
            <my-empty></my-empty>
          </template>
        </view>
      </view>
    </scroll-view>
    <view
      v-if="visible"
      class="popup"
      :style="{ height: showMore ? '100%' : 'auto' }"
    >
      <view class="flex top">
        <view id="categorize" class="categorize-list flex-1">
          <view
            :class="[
              'categorize',
              currentCategorizeId == item.id ? 'active' : '',
            ]"
            v-for="(item, index) in formatPopupCategorizeList"
            :key="index"
            @click="switchCategorize(item)"
          >
            <text class="text">{{ item.name }}</text>
          </view>
        </view>
        <u-icon
          :name="showMore ? 'arrow-up' : 'arrow-down'"
          size="22"
          @click="showMore = !showMore"
        ></u-icon>
      </view>
      <view class="mask" v-if="showMore"></view>
    </view>
  </view>
</template>

<script setup>
import { goodsList } from "@/common/apis/goods.js";
import {
  computed,
  getCurrentInstance,
  nextTick,
  reactive,
  ref,
  watch,
} from "vue";

const instance = getCurrentInstance();

const props = defineProps({
  currentCategoryId: {
    type: [Number, String],
    default: "",
  },
  categorizeList: {
    type: Array,
    default: () => [],
  },
  categoriesHeight: {
    type: Number,
    default: 0,
  },
});

const currentCategorizeId = defineModel({ type: [Number, String] });

const categoriesHeight = ref(0);

const list = ref([]);

const totalPage = ref(0);

const visible = ref(false);

const showMore = ref(false);

const query = reactive({
  page: 1,
  size: 10,
});

// 监听三级分类id变化
watch(currentCategorizeId, (val) => {
  query.page = 1;
  query.size = 10;
  if (val) {
    fetchGetGoodsList();
  } else {
    list.value = [];
  }
});

const formatPopupCategorizeList = computed(() => {
  if (showMore.value) {
    return props.categorizeList;
  } else {
    return props.categorizeList.slice(0, 3);
  }
});

// 获取商品列表
async function fetchGetGoodsList(isCover = true) {
  uni.showLoading();
  const response = await goodsList({
    category: currentCategorizeId.value,
    ...query,
  });
  uni.hideLoading();
  if (response) {
    if (isCover) {
      list.value = response.records;
    } else {
      list.value = [...list.value, ...response.records];
    }
    totalPage.value = response.total_page;
    await nextTick();
    await getCategorizeHeight();
  }
}

// 切换分类
async function switchCategorize(item) {
  currentCategorizeId.value = item.id;
  await fetchGetGoodsList();
  showMore.value = false;
  visible.value = false;
}

function getCategorizeHeight() {
  return new Promise((resolve) => {
    uni
      .createSelectorQuery()
      .in(instance)
      .select("#categorize")
      .boundingClientRect((res) => {
        if (res) {
          categoriesHeight.value = res.height;
          resolve(res.height);
        }
      })
      .exec();
  });
}

function handleScroll(e) {
  visible.value = e.detail.scrollTop > categoriesHeight.value;
}

function handleScrollToLolower() {
  if (query.page < totalPage.value) {
    query.page++;
    fetchGetGoodsList(false);
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: 100%;
  background-color: #fff;
  position: relative;

  .scroll-wrapper {
    .categorize-list {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
      // 原有的 padding 可根据实际情况调整
      padding: 20rpx;

      .categorize {
        // 计算每个元素的宽度，每行 3 个元素，减去间隔宽度
        width: calc((100% - 40rpx) / 3);
        box-sizing: border-box;
        padding: 10rpx;
        background-color: #f7f7f7;
        border-radius: 10rpx;
        padding: 5px 0px;
        color: #333333;
        font-size: 12px;
        text-align: center;

        .text {
          display: block;
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        &.active {
          background-color: $u-primary;
          color: #ffffff;
        }
      }
    }
  }

  .popup {
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    display: flex;
    flex-direction: column;

    .top {
      background-color: #ffffff;
      padding-right: 20rpx;

      .categorize-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        // 原有的 padding 可根据实际情况调整
        padding: 20rpx;

        .categorize {
          // 计算每个元素的宽度，每行 3 个元素，减去间隔宽度
          width: calc((100% - 40rpx) / 3);
          // 计算每个元素的宽度，每行 3 个元素，减去间隔宽度
          box-sizing: border-box;
          padding: 10rpx;
          background-color: #f7f7f7;
          border-radius: 10rpx;
          padding: 5px 0px;
          color: #333333;
          font-size: 12px;
          text-align: center;

          .text {
            display: block;
            width: 100%;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          &.active {
            background-color: $u-primary;
            color: #ffffff;
          }
        }
      }
    }

    .mask {
      flex: 1;
      background-color: rgba(0, 0, 0, 0.3);
    }
  }
}
</style>
